package elitequant.gui;

import java.awt.BorderLayout;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import elitequant.event.Event;
import elitequant.event.EventHandler;
import elitequant.event.EventType;
import elitequant.event.LiveEventEngine;
import elitequant.order.FillEvent;
import elitequant.util.UtilFunc;

public class FillWindow extends JPanel implements EventHandler {

    private LiveEventEngine eventsEngine;

    private JTable jTable;

    private DefaultTableModel tableModel;

    private String[] header = new String[] { "OrderID", "Symbol", "FillTime",
            "FillPrice", "FillSize" };

    public FillWindow(LiveEventEngine eventsEngine) {
        this.eventsEngine = eventsEngine;

        initTable();

        registerEvent();
    }

    private void initTable() {
        setLayout(new BorderLayout());

        tableModel = new DefaultTableModel();
        jTable = new JTable(tableModel);
        jTable = new JTable(tableModel) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        tableModel.setDataVector(new String[0][0], header);

        jTable.setFillsViewportHeight(true);

        JScrollPane scrollPane = new JScrollPane(jTable);
        add(scrollPane);
    }

    private void registerEvent() {
        eventsEngine.registerHandler(EventType.FILL, this);
    }

    private void updateTable(FillEvent fillEvent) {
        tableModel.addRow(new String[] {
                String.valueOf(fillEvent.brokerOrderId), fillEvent.fullSymbol,
                UtilFunc.formatDate(fillEvent.timestamp),
                UtilFunc.formatMoney(fillEvent.fillPrice),
                String.valueOf(fillEvent.fillSize) });
    }

    @Override
    public void handle(Event event) {
        if (event.getClass().isAssignableFrom(FillEvent.class)) {
            updateTable((FillEvent) event);
        }

    }

}
